package com.shanghaionstar.nav;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.onstar.cn.auth.userProfile.FeatureEnum;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PayMeConstants;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.ripple.view.RippleCustomBtn;
import com.onstar.cn.rxconstants.RxConstants;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.VehicleLoadingActivity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.iview.ILoginAndOutListener;
import com.shanghaionstar.iview.ILoginListener;
import com.shanghaionstar.nav.iview.INavPoiDetailView;
import com.shanghaionstar.nav.presenter.NavPoiDetailPresenter;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.nav.share.SharePoiDialog;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.LoadCityList;
import com.shanghaionstar.utils.LoginUtil;
import com.shanghaionstar.utils.MapHandler;
import com.shanghaionstar.weight.TopLayout;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;


/**
 * Created by 6335yz on 2016/7/18.
 */
public class NavPoiDetailFragment extends BaseFragment implements INavPoiDetailView, ILoginAndOutListener, ILoginListener {

    @FindViewById(R.id.text_shap_name)
    private TextView text_shap_name;//商家名称
    @FindViewById(R.id.text_address_info)
    private TextView text_address_info;//商家地址信息
    @FindViewById(R.id.text_call_info)
    private TextView text_call_info;//商家电话
    @FindViewById(R.id.dealer_distance)
    private TextView dealer_distance;

    //发送到音控导航
    @FindViewById(R.id.btn_send_tbt)
    private RippleCustomBtn btn_send_tbt;
    //发送到车载导航
    @FindViewById(R.id.btn_send_odd)
    private RippleCustomBtn btn_send_odd;

    @FindViewById(R.id.btn_around_search)
    private RippleCustomBtn btn_around_search;//周边检索
    @FindViewById(R.id.btn_around_dealer)
    private RippleCustomBtn btn_around_dealer;//周边经销商
    @FindViewById(R.id.btn_route_plan)
    private RippleCustomBtn btn_route_plan;//路线规划
    @FindViewById(R.id.btn_collect_bourn)
    private RippleCustomBtn btn_collect_bourn;//收藏目的地
    private String myLocationInfo;
    private PoiItemInfo poiItemInfo;
    private IWXAPI weiXinApi;
    private String weiXinAppId = PayMeConstants.APP_ID;
    private String dealer_distance_info = "";
    private AbstractMapActivity mapActivity;
    private NavPoiDetailPresenter navPoiDetailPresenter;
    private MapHandler mapHandler;
    private FragmentManager fragmentManager;
    @FindViewById
    private TopLayout top_layout;

    private LoginUtil mLoginUtil;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getArguments() != null) {
            poiItemInfo = (PoiItemInfo) getArguments().get(Constants.POIITEMINFO);
            navPoiDetailPresenter = new NavPoiDetailPresenter(mapActivity.getScheduler(), mapActivity, mapHandler);
            navPoiDetailPresenter.setView(this);
            showPoiDetail(poiItemInfo);
            top_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.POIdetail_returenicon.getStringValue());
                    goBack();
                }
            });
            top_layout.setOnRightTextClickLstener(baseActivity.getString(R.string.share), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.POIdetail_share.getStringValue());
                    showShareDialog(mapHandler.getMapPoi_PoiItemInfo());
                }
            });
            mLoginUtil = new LoginUtil();
            mLoginUtil.loginAndOutShowView(baseActivity, this);
            new LoginUtil().registLoginResult(this);
        }
    }

    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mapActivity = (AbstractMapActivity) activity;
        mapHandler = mapActivity.getMapHandler();
        fragmentManager = mapActivity.getSupportFragmentManager();

    }

    @Override
    public int getLayoutId() {
        return R.layout.nav_poi_detail;
    }

    SharePoiDialog sharePoiDialog;

    private void showShareDialog(PoiItemInfo shareItemInfo) {
        if (sharePoiDialog == null) {
            sharePoiDialog = new SharePoiDialog(getContext(), R.style.ShareDialog, shareItemInfo);
            Window window = sharePoiDialog.getWindow();
            window.setGravity(Gravity.BOTTOM);  //此处可以设置dialog显示的位置
            window.setWindowAnimations(R.style.ShareDialog_Animation);  //添加动画
//            sharePoiDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
//                @Override
//                public void onDismiss(DialogInterface dialog) {
//                    dimBackground(0.5f, 1f);
//                }
//            });
        }
//        dimBackground(1f, 0.5f);
        sharePoiDialog.show();
    }

    @Override
    public void showPoiDetail(@NonNull PoiItemInfo poiItemInfo) {
        weiXinApi = WXAPIFactory.createWXAPI(mapActivity, weiXinAppId, true);
        text_shap_name.setText(poiItemInfo.getTitle());
        if (poiItemInfo.getAddress() == null || poiItemInfo.getAddress().trim().equals("")) {
            text_address_info.setText(R.string.poi_null_data);
        } else {
            text_address_info.setText(poiItemInfo.getAddress());
        }
        if (poiItemInfo.getTelphone() != null && !CommonUtil.isNull(poiItemInfo.getTelphone().split(";"))) {
            text_call_info.setText(poiItemInfo.getTelphone().split(";")[0]);
        }
        if (poiItemInfo.getTelphone() == null || poiItemInfo.getTelphone().trim().equals("")) {
            text_call_info.setText(R.string.poi_null_data);
        }
        if (!CommonUtil.isNull(dealer_distance_info)) {
            dealer_distance.setText(dealer_distance_info);
        } else {
            dealer_distance.setText("");
        }
    }

    @Override
    public void showShareViewDialog() {

    }

    @Override
    public void showOddBtn(boolean isShow) {
        btn_send_odd.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    @Override
    public void updateButtonState(Button button) {

    }

    @Override
    public void shareToWX() {

    }

    @Override
    public void shareToWXF() {

    }

    @Override
    public void setLoading(boolean isLoading) {

    }

    @Override
    public void onResponseError(OnStarException e) {

    }

    @Override
    public void onReponseSuccess(Object object) {

    }

    @Override
    public Activity onActivity() {
        return null;
    }


    @OnClick({R.id.text_call_info,
            R.id.btn_send_tbt,
            R.id.btn_send_odd,
            R.id.btn_around_search,
            R.id.btn_around_dealer,
            R.id.btn_route_plan,
            R.id.btn_collect_bourn
    })
    public void OnClick(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.text_call_info://拨打商家电话
                BusinessUtil.sendReportByClickType(mapActivity,
                        FunctionNameFindId.POIdetail_dialicon.getStringValue());
                String phone = text_call_info.getText().toString();
                if (!"----".equals(phone)) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + phone));
                    startActivity(intent);
                }
                break;
            case R.id.btn_send_tbt://音控导航
                BusinessUtil.sendReportByRequestParams(mapActivity, FunctionNameFindId.POIdetail_TBT.getStringValue(),
                        ReportReqParam.getTBTOddClickParams(FunctionNameFindId.POIdetail_TBT.getStringValue(),
                                mapHandler.getMapPoi_PoiItemInfo() == null ? 0 : mapHandler.getMapPoi_PoiItemInfo().getLatitude(),
                                mapHandler.getMapPoi_PoiItemInfo() == null ? 0 : mapHandler.getMapPoi_PoiItemInfo().getLongitude()));
                bundle.putInt("commands", R.id.btn_send_tbt);
                new LoginUtil().loginAndActionCallBack(baseActivity, RxConstants.NAV_POI_DETAIL_PAGE, this, bundle);
                break;
            case R.id.btn_send_odd://发送到车载导航
                BusinessUtil.sendReportByRequestParams(mapActivity, FunctionNameFindId.POIdetail_ODD.getStringValue(),
                        ReportReqParam.getTBTOddClickParams(FunctionNameFindId.POIdetail_ODD.getStringValue(),
                                mapHandler.getMapPoi_PoiItemInfo() == null ? 0 : mapHandler.getMapPoi_PoiItemInfo().getLatitude(),
                                mapHandler.getMapPoi_PoiItemInfo() == null ? 0 : mapHandler.getMapPoi_PoiItemInfo().getLongitude()));
                bundle.putInt("commands", R.id.btn_send_odd);
                new LoginUtil().loginAndActionCallBack(baseActivity, RxConstants.NAV_POI_DETAIL_PAGE, this, bundle);
                break;
            case R.id.btn_around_search://周边检索
                BusinessUtil.sendReportByClickType(mapActivity,
                        FunctionNameFindId.POIdetail_aroundsearch.getStringValue());
                mapActivity.addFragment(fragmentManager, new NavSearchMoreFragment(), true);
                mapActivity.showFragment(fragmentManager, NavSearchMoreFragment.class, NavPoiDetailFragment.class);
                break;
            case R.id.btn_around_dealer://周边经销商
                BusinessUtil.sendReportByClickType(mapActivity,
                        FunctionNameFindId.POIdetail_arounddealer.getStringValue());
                if (mapActivity.getNavDataHolder().getCurrentMapPoi() != null) {
                    mapActivity.addFragment(fragmentManager, NavAroundDealerFragment.newInstance(mapActivity.getNavDataHolder().getCurrentMapPoi()), true);
                    mapActivity.showFragment(fragmentManager, NavAroundDealerFragment.class, NavPoiDetailFragment.class);
                }
                break;
            case R.id.btn_route_plan://路线规划
                PoiItemInfo currentMapPoi = mapActivity.getNavDataHolder().getCurrentMapPoi();
                if (!CommonUtil.isNull(currentMapPoi)) {
                    BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.POIdetail_routeplanning.getStringValue());
                    if (DeviceUtil.getLanguage().equalsIgnoreCase("en")) {
                        LoadCityList loadCityList = new LoadCityList(mapActivity);
                        currentMapPoi.setCityName(loadCityList.findByZhCity(currentMapPoi.getCityName()));
                    }
                    mapActivity.addFragment(fragmentManager, NavRoutePlanFragment.newInstance(currentMapPoi), true);
                    mapActivity.showFragment(fragmentManager, NavRoutePlanFragment.class, NavPoiDetailFragment.class);
                }
                break;
            case R.id.btn_collect_bourn://收藏目的地
                BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.POIdetail_favorite.getStringValue());
                bundle.putInt("commands", R.id.btn_collect_bourn);
                new LoginUtil().loginAndActionCallBack(baseActivity, RxConstants.NAV_POI_DETAIL_PAGE, this, bundle);
                break;
        }
    }

    public static NavPoiDetailFragment newInstance(PoiItemInfo poiItemInfo) {
        NavPoiDetailFragment navPoiDetailFragment = new NavPoiDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("poiItemInfo", poiItemInfo);
        navPoiDetailFragment.setArguments(bundle);
        return navPoiDetailFragment;
    }

    @Override
    public void showCommandLoading(boolean isShow) {
        if (isShow) {
            startActivity(new Intent(mapActivity, VehicleLoadingActivity.class));
        }
    }

    @Override
    public void onLogin() {
        if (BusinessUtil.isServiceFeature(FeatureEnum.SENDNAVDESTINATION.value(), mapActivity)) {
            showOddBtn(true);
        } else {
            showOddBtn(false);
        }
    }

    @Override
    public void onLoginOut() {
        showOddBtn(false);
    }

    @Override
    public void onLogin(Bundle bundle, String resultCode) {
        if (RxConstants.ACTION_SUCCESS.equals(resultCode)) {
            if (bundle != null) {
                int id = bundle.getInt("commands");
                switch (id) {
                    case R.id.btn_collect_bourn:
                        mapActivity.addFragment(fragmentManager, NavFavSaveFragment.newInstance(poiItemInfo), true);
                        mapActivity.showFragment(fragmentManager, NavFavSaveFragment.class, NavPoiDetailFragment.class);
                        break;
                    case R.id.btn_send_tbt:
                        navPoiDetailPresenter.sendTbtOrOdd(poiItemInfo, RemoteCommandsType.COMMANDS_TBT_ROUTE);
                        break;
                    case R.id.btn_send_odd:
                        navPoiDetailPresenter.sendTbtOrOdd(poiItemInfo, RemoteCommandsType.COMMANDS_NAV_DESTINATION);
                        break;
                }
            }
        }
    }

    /**
     * 调整窗口的透明度
     *
     * @param from>=0&&from<=1.0f
     * @param to>=0&&to<=1.0f
     */
    private void dimBackground(final float from, final float to) {
        final Window window = mapActivity.getWindow();
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(from, to);
        valueAnimator.setDuration(500);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                WindowManager.LayoutParams params = window.getAttributes();
                params.alpha = (Float) animation.getAnimatedValue();
                window.setAttributes(params);
            }
        });
        valueAnimator.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mLoginUtil != null)
            mLoginUtil.clearLoginOrOut();
    }
}
